package com.gao.a_image2text;

import com.gao.a_image2text.util.AuthService;
import com.gao.a_image2text.util.Base64Util;
import com.gao.a_image2text.util.FileUtil;
import com.gao.a_image2text.util.HttpUtil;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 身份证识别
 */
public class Idcard {

    public static String idcard() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        try {
            // 本地文件路径
            String filePath = "F:\\身份证测试\\正面.png";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "id_card_side=" + "front" + "&image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();

            String result = HttpUtil.post(url, accessToken, param);
            // System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String idcard = Idcard.idcard();
        System.out.println("idcard = " + idcard);
        String[] keys = "住址 出生 姓名 公民身份号码 性别 民族".split(" ");
        Map<String, String> idcardMap = new HashMap<String, String>();
        for (String key : keys) {
            Pattern p = Pattern.compile(key + ".*?\"words\": \"(.*?)\"");
            Matcher matcher = p.matcher(idcard);
            if (matcher.find()) {
                String value = matcher.group(1);
                //System.out.println(key + " = " + value);
                idcardMap.put(key, value);
            }
        }
        System.out.println(idcardMap);
    }
}
